package com.epalmpay.controller.apipos;

import com.alibaba.fastjson.JSON;
import com.epalmpay.commom.BaseController;
import com.epalmpay.dto.posapi.PosApiRequestDTO;
import com.epalmpay.dto.posapi.PosApiResponseDTO;
import com.epalmpay.service.posapi.PosApiService;
import com.epalmpay.util.payplat.MapUtil;
import com.epalmpay.util.payplat.SecurityUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Map;

/**
 * Created by lifayi on 2017/6/16.
 */
@RestController
@RequestMapping("/service/api")
public class PosApiController extends BaseController {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
    private PosApiService posApiService;

    @Value("${POS_VERIFY_KEY}")
    private String posVerifyKey;

    @RequestMapping(value = "/pos", method = RequestMethod.POST)
    public PosApiResponseDTO posApiUnionGateway(@RequestBody PosApiRequestDTO posApiRequestDTO) throws Exception {
        PosApiResponseDTO posApiResponseDTO = new PosApiResponseDTO();
        posApiResponseDTO.setCode("400");
        posApiResponseDTO.setMsg("请求非法");

        String cmd = posApiRequestDTO.getCmd();
        posApiResponseDTO.setCmd(cmd);

        Map<String, Object> params = posApiRequestDTO.getParams();
        if(cmd == null || params == null) {
            return posApiResponseDTO;
        }

        if(params.get("verify") == null) {
            return posApiResponseDTO;
        }

        //请求参数防篡改验证
        if(!checkVerify(params)) {
            posApiResponseDTO.setCode("415");
            posApiResponseDTO.setMsg("参数验证错误");
            return posApiResponseDTO;
        }

        Map<String, Object> result;
        switch(cmd) {
            case "posSignIn":
                result = posApiService.posSignIn(params);
                break;
            case "benefits":
                result = posApiService.benefits(params);
                break;
            case "tranMoney":
                result = posApiService.tranMoney(params);
                break;
            case "tranUploadPos":
                result = posApiService.tranUploadPos(params);
                break;
            case "getPrintData":
                result = posApiService.getPrintData(params);
                break;
            case "qbPay":
                result = posApiService.qbPay(params);
                break;
            case "icCardPay":
                result = posApiService.icCardPay(params);
                break;
            case "icCardPayApp":
                result = posApiService.icCardPayApp(params);
                break;
            case "qbQuery":
                result = posApiService.qbQuery(params);
                break;
            case "trade_packet_cancel":
                result = posApiService.tradePacketCancel(params);
                break;
            case "trade_cancel":
                result = posApiService.tradeCancel(params);
                break;
            case "shift_time":
                result = posApiService.shiftTime(params);
                break;
            case "new_card":
                result = posApiService.newCard1(params);
                break;
            case "confirm_bind_card":
                result = posApiService.confirmBindCard(params);
                break;
            case "change_card":
                result = posApiService.changeCard(params);
                break;
            case "get_recharge_info":
                result = posApiService.getRechargeInfo(params);
                break;
            case "rechargeAmountQuery":
                result = posApiService.rechargeAmountQuery(params);
                break;
            case "rechargeTradeUpload":
                result = posApiService.saveRechargeTradeUpload(params);
                break;
            case "changePassword":
                try {
                    result = posApiService.saveChangePassword(params);
                } catch (Exception e) {
                    e.printStackTrace();
                    result = null;
                }
                break;
            case "couponInfo":
                result = posApiService.couponInfo(params); 
                break;
            case "couponVerify":
                result = posApiService.couponVerify(params,ROOT_HOME_URL);//券码核销
                break;
            case "couponRefund":
                result = posApiService.couponRefund(params);
                break;
            case "otherCouponInfo":
                result = posApiService.otherCouponInfo(params);
                break;
            case "otherCouponLock":
                result = posApiService.otherCouponLock(params);
                break;
            case "orderCancel":
                result = posApiService.orderCancel(params);
                break;
            case "tranUpload":
                result = posApiService.tranUpload(params);
                break;
            default:
                return posApiResponseDTO;
        }

        if(result != null) {
            if((Integer)result.get("responseCode") == 1) {
                result.remove("responseCode");
                posApiResponseDTO.setResult(result);
                logger.debug(JSON.toJSONString(result));
                posApiResponseDTO.setCode("A00006");
                posApiResponseDTO.setMsg("成功");
            } else {
                posApiResponseDTO.setCode(result.get("responseCode").toString());
                posApiResponseDTO.setMsg((String) result.get("responseMsg"));
            }
        }

        return posApiResponseDTO;
    }

    private Boolean checkVerify(Map<String, Object> params) {
        String verifyStr = (String) params.remove("verify");
        Map<String, Object> sortedParams = MapUtil.orderMap(params);
        StringBuffer stringBuffer = new StringBuffer();
        for(Map.Entry<String, Object> sortedParam : sortedParams.entrySet()) {
            if(sortedParam.getValue() != null) {
                String value = sortedParam.getValue().toString();
                stringBuffer.append(value);
            }
        }
        stringBuffer.append(posVerifyKey);  //连接pos验证key
        String md5ParamsValue = SecurityUtil.md5LowerCase(stringBuffer.toString());
        return verifyStr.equals(md5ParamsValue);
    }
}
